package servlet.Visitor;

import com.jspsmart.upload.SmartUpload;
import domain.Room;
import service.visitor.VisitorService;
import service.visitor.VisitorServiceImpl;
import util.IpTimeStamp;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.PageContext;
import java.io.IOException;
import java.net.InetAddress;

public class UpdateVisitor extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public UpdateVisitor() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        String phone = null;
        String carid = null;
        String idcard = null;
        String cometime = null;
        String validtime = null;
        String reason = null;
        String photo_img = null;
        VisitorService visitorService = new VisitorServiceImpl();
        SmartUpload smart = new SmartUpload();
        if(request.getSession().getAttribute("userloginflag")==null){
            request.getRequestDispatcher("/index.jsp").forward(request, response);
        }else {
            Room room = (Room)request.getSession().getAttribute("userloginflag");
            try {
                //PageContext是jsp的内置对象，在servlet不能直接使用，需要做一些处理
                JspFactory _jspxFactory = null;
                PageContext pageContext = null;
                _jspxFactory = JspFactory.getDefaultFactory();
                pageContext = _jspxFactory.getPageContext(this, request, response, "", true, 8192, true);

                smart.initialize(pageContext);//初始化上传操作
                // 设定上传限制
                // 1.限制每个上传文件的最大长度。

                // 2.限制总上传数据的长度。

                // 3.设定允许上传的文件（通过扩展名限制）,仅允许doc,txt文件。

                smart.upload();
                IpTimeStamp its = new IpTimeStamp(InetAddress.getLocalHost().getHostAddress());//request.getRemoteAddr()获得用户的ip地址
                //System.out.println("获取的ip为"+InetAddress.getLocalHost().getHostAddress());
                //如果要实现文件的批量上传，则只需用for循环，将getFile(0)中的0改为i即可
                String ext1 = smart.getFiles().getFile(0).getFileExt();//此为得到文件的扩展名,getFile(0)为得到唯一的一个上传文件
                if (ext1.length()>1) {
                    String ip = its.getIpTimeRand();
                    String fileName1 = "FkPhoto" + ip + "." + ext1;
                    //System.out.println("获取 的文件名为"+fileName);
                    //this.getServletContext().getRealPath("/")为得到tomcat的跟目录，放于upload文件夹中，java.io.File.separator是一种安全操作
                    //String realPath="";
                    //this.getServletContext().getRealPath("/")+
                    smart.getFiles().getFile(0).saveAs(this.getServletContext().getRealPath("/") + "uploadFile" + java.io.File.separator + fileName1);
                    photo_img = "uploadFile/" + fileName1 + "";
                }
                //
                //由于前面的form表单已经进行了封装，这里就不能简单的用request.getparameter()来获取表单参数
                phone = smart.getRequest().getParameter("phone");
                carid = smart.getRequest().getParameter("carid");
                idcard = smart.getRequest().getParameter("idcard");
                cometime = smart.getRequest().getParameter("cometime");
                validtime = smart.getRequest().getParameter("validtime")+"小时";
                reason = smart.getRequest().getParameter("reason");

            } catch (Exception e) {
                e.printStackTrace(); //code
            } finally {
                // add this section
            }
            if (phone == null || carid == null || idcard == null || cometime==null || validtime==null || reason ==null ||request.getParameter("visitors_id")==null) {
                System.out.println("删除，异常操作！");
                request.getRequestDispatcher("/admin/error/error404.jsp").forward(request, response);
                return;
            }else {
                int visitors_id = Integer.parseInt(request.getParameter("visitors_id"));
                int i = visitorService.UpdateVisitor(visitors_id,phone,idcard,carid,photo_img,reason,cometime,validtime);
                if (i > 0) {
                    request.setAttribute("message", "新增成功");
                    request.getRequestDispatcher("VisitorInfo").forward(request, response);
                    return;
                } else {
                    request.setAttribute("message", "网络故障");
                    request.getRequestDispatcher("VisitorInfo").forward(request, response);
                    return;
                }
            }
            }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }
}